/*
 *                  BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 * 
 * Created on Nov 2, 2007
 * 
 */

package org.biojava.services.das.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.biojava.services.das.registry.DasRegistrySql;

public class NewsManager {
	
	public static Logger logger =  Logger.getLogger("org.biojava.services.das.registry");
	
	DataSource dataSource;
	
	NewsDAO dao;
	
	
	public NewsManager() {
		try {
			Context env = (Context) new InitialContext().lookup("java:comp/env");
			//logger.info("init dataSource");
			dataSource = (DataSource) env.lookup(DasRegistrySql.DATASOURCE_NAME);
			if (dataSource == null) {
				logger.severe("could not obtain the dataSource -there will be serious problems. is the config correct?");
			}
			//logger.info(dataSource.toString());

		} catch (Exception ex) {
			ex.printStackTrace();
			//System.err.println("ERROR:could not init DasRegistrySql DB dataSource!");
			logger.severe("could not init datasource!");
		}
		
		dao = new NewsDAO();
	}


	public List<NewsItem> getAllNews(){


		Connection conn = null;
		List<NewsItem> newsList = new ArrayList<NewsItem>();
		try {
			conn = dataSource.getConnection();
			newsList = dao.getAllNews(conn);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null){
				try {
					conn.close();
				} catch (SQLException e){
					e.printStackTrace();
				}
			} 
		}
		
		return newsList;
	}

	public NewsItem getNewsByID(int newsID){


		Connection conn = null;
		NewsItem news = null;
		try {
			conn = dataSource.getConnection();
			news = dao.getNewsByID(conn, newsID);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null){
				try {
					conn.close();
				} catch (SQLException e){
					e.printStackTrace();
				}
			} 
		}
		
		return news;
	}

	
	
}
